import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  operationStatusEnum,
  lampPostTypeEnum,
  lampBaseTypeEnum
} from '~/store/assetManagement/facilityManagement/typings'
import type { PowerDistributionFacilitiesDataItemType } from '../../facilityManagement/powerDistributionFacilities/typings'
import type { AssociatedFacilitiesDataItemType, AssociatedFacilitiesActiveTabKey } from './typings'
import type { FormInstance } from 'element-plus'
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElTabs,
  ElTabPane,
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElLink
} from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import ColorfulBadge from '~/components/ColorfulBadge'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_SIX } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'AssociatedFacilities',
  props: ['detail'],
  setup(props: { detail: PowerDistributionFacilitiesDataItemType }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const lightPoleProSaasTableRef = ref<ProSaasTableExposeType>()
    const lampProSaasTableRef = ref<ProSaasTableExposeType>()
    const activeTabKeyRef = ref<AssociatedFacilitiesActiveTabKey>('lightPole')
    const formValues = reactive<AssociatedFacilitiesDataItemType>({})
    const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
      'operationStatusSelectList',
      'operationStatusEnum'
    ])
    const assetLampPostState = useVuexGetters('assetLampPost', [
      'lampPostTypeSelectList',
      'lampPostTypeEnum'
    ]) // 灯杆类型
    const assetLampBaseState = useVuexGetters('assetLampBase', [
      'lampBaseTypeSelectList',
      'lampBaseTypeEnum'
    ]) // 灯具类型

    // 切换tab
    const handleChangeActiveTab = () => {
      ruleFormRef.value?.resetFields()
      activeTabKeyRef.value === 'lightPole'
        ? lightPoleProSaasTableRef.value?.toSearch()
        : lampProSaasTableRef.value?.toSearch()
    }

    // 查询列表
    const handleSearchTableList = () => {
      nextTick(() => {
        activeTabKeyRef.value === 'lightPole'
          ? lightPoleProSaasTableRef.value?.toSearch()
          : lampProSaasTableRef.value?.toSearch()
      })
    }

    onMounted(() => {
      if (!assetLampPostState.lampPostTypeSelectList?.length)
        store.dispatch('assetLampBase/GetNodeByParentCode') // 灯具类型 下拉列表
      if (!assetLampBaseState.lampBaseTypeSelectList?.length)
        store.dispatch('assetLampPost/GetNodeByParentCode') // 灯杆类型 下拉列表
    })

    const lightPoleColumns: TableColumnProps<AssociatedFacilitiesDataItemType>[] = [
      {
        label: '名称',
        prop: 'name'
      },
      {
        label: '所属回路',
        prop: 'distributionLoopName',
        align: 'center',
        sortable: true
      },
      {
        label: '杆号',
        prop: 'code',
        sortable: true
      },
      {
        label: '类型',
        prop: 'categoryId',
        enumValues: assetLampPostState.lampPostTypeEnum,
        sortable: true
      }
      // {
      //   label: 'UID',
      //   prop: 'uid'
      // }
    ]

    const lampColumns: TableColumnProps<AssociatedFacilitiesDataItemType>[] = [
      {
        label: '名称',
        prop: 'name'
      },
      {
        label: '状态',
        prop: 'isDeliver',
        enumValues: powerDistributionFacilitiesState.operationStatusEnum,
        sortable: true,
        render: (option, value) => (
          <ColorfulBadge
            value={value}
            enumKey={(option.row.isDeliver as number) || 0}
            options={{ warning: 0, success: 1, info: 2 }}
          />
        )
      },
      {
        label: '类型',
        prop: 'categoryId',
        enumValues: assetLampBaseState.lampBaseTypeEnum,
        sortable: true
      }
      // {
      //   label: 'UID',
      //   prop: 'uid'
      // }
    ]

    return () => (
      <ElForm ref={ruleFormRef} model={formValues} class={styles['info-content-height-full-box']}>
        <ElTabs
          class={[styles['associated-facilities-tab'], 'covered-with-tabs']}
          v-model={activeTabKeyRef.value}
          onTab-change={handleChangeActiveTab}
        >
          <ElTabPane name="lightPole" label="灯杆">
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_SIX}>
                <ElFormItem prop="name">
                  <ElInput
                    v-model={formValues.name}
                    placeholder="名称/灯杆 回车搜索"
                    onKeydown={(event: Event | KeyboardEvent) =>
                      (event as KeyboardEvent).key === 'Enter' && handleSearchTableList()
                    }
                    v-slots={{
                      suffix: () => (
                        <ElLink
                          type="info"
                          underline={false}
                          icon={<AliIcon type="icon-sousuo" />}
                          onClick={handleSearchTableList}
                        />
                      )
                    }}
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_SIX}>
                <ElFormItem prop="categoryId">
                  <ElSelect
                    v-model={formValues.categoryId}
                    placeholder="请选择类型"
                    clearable
                    onChange={handleSearchTableList}
                  >
                    {assetLampPostState.lampPostTypeSelectList?.value?.map(
                      (item: lampPostTypeEnum) => (
                        <ElOption key={item?.id} label={item?.dictValue} value={item?.id!} />
                      )
                    )}
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ProSaasTable<AssociatedFacilitiesDataItemType>
              // tableId="associatedFacilities-lightPole"
              ref={lightPoleProSaasTableRef}
              columns={lightPoleColumns}
              rowKey="id"
              hasSelection
              defaultSort={{ prop: 'code', order: 'ascending' }}
              dispatchType={'assetLampPost/GetAssetLampPostList'}
              searchFormProps={{
                model: formValues
              }}
              searchParams={{
                name: formValues.name && handleTrim(formValues.name),
                distributionId: props.detail.id
              }}
            />
          </ElTabPane>
          <ElTabPane name="lamp" label="灯">
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_SIX}>
                <ElFormItem prop="name">
                  <ElInput
                    v-model={formValues.name}
                    placeholder="名称 回车搜索"
                    onKeydown={(event: Event | KeyboardEvent) =>
                      (event as KeyboardEvent).key === 'Enter' && handleSearchTableList()
                    }
                    v-slots={{
                      suffix: () => (
                        <ElLink
                          type="info"
                          underline={false}
                          icon={<AliIcon type="icon-sousuo" />}
                          onClick={handleSearchTableList}
                        />
                      )
                    }}
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_SIX}>
                <ElFormItem prop="isDeliver">
                  <ElSelect
                    v-model={formValues.isDeliver}
                    placeholder="请选择状态"
                    clearable
                    onChange={handleSearchTableList}
                  >
                    {powerDistributionFacilitiesState.operationStatusSelectList?.value?.map(
                      (item: operationStatusEnum) => (
                        <ElOption
                          key={item?.dictKey}
                          label={item?.dictValue}
                          value={item?.dictKey!}
                        />
                      )
                    )}
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_SIX}>
                <ElFormItem prop="categoryId">
                  <ElSelect
                    v-model={formValues.categoryId}
                    placeholder="请选择类型"
                    clearable
                    onChange={handleSearchTableList}
                  >
                    {assetLampBaseState.lampBaseTypeSelectList?.value?.map(
                      (item: lampBaseTypeEnum) => (
                        <ElOption key={item?.id} label={item?.dictValue} value={item?.id!} />
                      )
                    )}
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ProSaasTable<AssociatedFacilitiesDataItemType>
              // tableId="associatedFacilities-lamp"
              ref={lampProSaasTableRef}
              columns={lampColumns}
              rowKey="id"
              hasSelection
              defaultSort={{ prop: 'isDeliver', order: 'ascending' }}
              dispatchType={'assetLampBase/GetAssetLampBaseList'}
              searchFormProps={{
                model: formValues
              }}
              searchParams={{
                name: formValues.name && handleTrim(formValues.name),
                distributionId: props.detail.id
              }}
            />
          </ElTabPane>
        </ElTabs>
      </ElForm>
    )
  }
})
